<template>
  <div class="theme-content">
    <div class="theme-content-item" style="position: relative;">
      <div class="padding-20px">
        <div class="left-title">题库信息</div>
        <el-form ref="questionAddRef" :model="questionAddRequest" :rules="rules" label-width="120px"
          class="demo-ruleForm grid-clo-2-30" :size="'default'" style="justify-content: center;grid-gap:0 125px"
          status-icon>
          <el-form-item label="所属类目" prop="categoryId">
            <el-select @change="initCourseOtherOption()" style="width: 400px;" v-model="questionAddRequest.categoryId"
              placeholder="请选择所属类目">
              <el-option v-for="item, index in saveOptions.courseOption" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属类别" prop="courseParentId">
            <el-select :disabled="saveOptions.courseOtherOption.length == 0"
              @change="initCourseBankTypeOption(), initSubOption()" v-model="questionAddRequest.courseParentId"
              placeholder="请选择所属类别">
              <el-option v-for="item, index in saveOptions.courseOtherOption" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <!-- subOption -->
          <el-form-item label="所属科目" prop="courseId">
            <el-select v-model="questionAddRequest.courseId" placeholder="请选择所属科目"
              :disabled="saveOptions.courseBankTypeOption.length == 0">
              <el-option v-for="item, index in saveOptions.subOption" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="题库类型" prop="courseBankTypeId">
            <el-select :disabled="saveOptions.courseBankTypeOption.length == 0"
              v-model="questionAddRequest.courseBankTypeId" placeholder="请选择题库类型">
              <el-option v-for="item, index in saveOptions.courseBankTypeOption" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input :maxlength="1000" v-model="questionAddRequest.remark" :rows="2" type="textarea"
              placeholder="请填写备注" />
          </el-form-item>
        </el-form>
        <div class="left-title">试题导入</div>
        <div class="flex-center">
          <div class="questionAdd-item" style="border: 1px solid rgba(28,175,154,0.502);">
            <img src="@/assets/images/downCloud.png" alt="">
            <el-button class="questionAdd-button-item" @click="fileDownload" type="primary">下载Excel模版</el-button>
          </div>
          <div class="questionAdd-item">
            <img src="@/assets/images/upCloud.png" alt="">
            <el-upload v-model:file-list="fileList" accept=".xls,.xlsx" ref="uploadRef" class="upload-demo" :action="uploadFileUrl"
              :headers="headers" :on-success="onSuccess" :before-upload="beforeUpload" :limit="9">
              <el-button class="questionAdd-button-item" type="primary">选择文件上传试题</el-button>
              <!-- <template #tip>
                <div class="el-upload__tip">
                </div>
              </template> -->
            </el-upload>
          </div>
        </div>
<!--        <div style="position: absolute;bottom:20px;right:100px">-->
<!--          <el-button @click="router.go(-1)">返回</el-button>-->
<!--        </div>-->
<!--        <div style="position: absolute;bottom:20px;right:20px">-->
<!--          <el-button type="primary" @click="confirmSave">确 定</el-button>-->
<!--        </div>-->
        <div style="width:151px; margin: auto;margin-top: 300px;" class="flex-jc-s-b">
          <div>
            <el-button @click="router.go(-1)">返 回</el-button>
          </div>
          <div>
            <el-button type="primary" @click="confirmSave">确 定</el-button>
          </div>
        </div>

      </div>
    </div>
    <!-- 上架失败 -->
    <el-dialog title="导入题库返回结果" v-model="resultReject">
      <div>
        <el-table :data="rejectList"
          :header-cell-style="{ 'text-align': 'center', 'background': '#fff', 'height': '44px' }"
          :cell-style="{ 'text-align': 'center', 'height': '44px' }" style="max-height:440px;overflow-y:scroll">
          <el-table-column label="行号" prop="orderNum"></el-table-column>
          <el-table-column label="失败原因">
            <template #default="scope">
              <span v-for="item, index in scope.row.messageList">{{ item }}{{ index == 0 ? '' : ',' }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer ">
          <el-button type="primary" @click="resultReject = false">
            确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { configListApi, enableBankTypeListApi, saveBankApi } from './const.js'
import { download } from '@/utils/request'
import { onMounted, reactive, ref, nextTick } from 'vue'
import { Plus, Search } from "@element-plus/icons-vue";
import { useRouter, useRoute } from 'vue-router'
import { getToken } from "@/utils/auth";
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
const route = useRoute()
const router = useRouter()
const questionAddRef = ref('')
const fileList = ref([])
let loading;
const rules = reactive({
  categoryId: [
    { required: true, message: '请选择所属类目', trigger: 'change' },
  ],
  courseParentId: [
    { required: true, message: '请选择所属类别', trigger: 'change' },
  ],
  courseBankTypeId: [
    { required: true, message: '请选择题目类型', trigger: 'change' },
  ],
  // courseId: [
  //   { required: true, message: '请选择所属科目', trigger: 'change' },
  // ],
})
const questionAddRequest = reactive({
  categoryId: '',
  courseParentId: '',
  courseBankTypeId: '',
  courseId: '',
  remark: '',
  file: [],
})
const saveOptions = reactive({
  courseOption: [],
  courseOtherOption: [],
  courseBankTypeOption: [],
  subOption: []
})
let fromDataRequest = new FormData()
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload");
const headers = ref({ Authorization: "Bearer " + getToken() });
onMounted(() => {
  initCourseOption()
})
const onSuccess = (uploadFile) => {
  ElMessage.success('上传成功')
  fileList.value = fileList.value.slice(-1)
  // fileList.value = []
  if (loading) {
    loading.close()
  }
}
const beforeUpload = (uploadFile) => {
  loading = ElLoading.service({ text: "正在上传数据，请稍候", background: "rgba(0, 0, 0, 0.7)", })
  if (fromDataRequest.get('file')) { fromDataRequest.set("file", uploadFile); }
  else { fromDataRequest.append("file", uploadFile); }
}
// 
const fileDownload = () => {
  if (!questionAddRequest.courseParentId) {
    ElMessage.warning('请选择所属类别')
    return
  }
  download('/bank/question/import/template/download',
    { "courseParentId": questionAddRequest.courseParentId || null, "courseId": questionAddRequest.courseId || null }, '导入题库模板下载',)
}
const rejectList = ref([])
const resultReject = ref(false)
const sendApi = () => {
  saveBankApi(fromDataRequest).then((res) => {
    ElMessage.success(res.msg || '操作成功')
    fromDataRequest.delete('file')
    for (const key in questionAddRequest) {
      questionAddRequest[key] = ''
      if (key != 'categoryId') { fromDataRequest.delete(key) }
    }
    loading.close()
    setTimeout(() => { if (questionAddRef.value) { questionAddRef.value.clearValidate(); fileList.value = [] } })
  }).catch((rej) => {
    loading.close(); rejectList.value = rej.rows || []
    resultReject.value = true
    if (rejectList.value.length > 0)
      rejectList.value.map(item => {
        item.orderNum = item.orderNum + 2
      })
  })
}
const confirmSave = async () => {
  if (!questionAddRef.value) return
  await questionAddRef.value.validate((valid, fields) => {
    if (!valid) { return }
    if (!fromDataRequest.get('file')) { ElMessage.warning('请选择上传文件'); return }
    if (fromDataRequest.get('courseParentId')) { sendApi(); return }
    for (const key in questionAddRequest) {
      if (key != 'categoryId') { fromDataRequest.append(key, questionAddRequest[key]) }
    }
    loading = ElLoading.service({ text: "加载中，请稍候", background: "rgba(0, 0, 0, 0.7)", })
    sendApi()
  })
}

// 清楚
const configRuleRequestClear = (type) => {
  switch (type) {
    case 'courseId': questionAddRequest.courseParentId = '', questionAddRequest.courseBankTypeId = '', questionAddRequest.courseId = ''
      break;
    case 'courseBankTypeId': questionAddRequest.courseBankTypeId = '', questionAddRequest.courseId = ''
      break;
    default: ''
  }
  if (questionAddRef.value) {
    let clearTime = null
    if (clearTime) { clearTimeout(clearTime); clearTime = null }
    clearTime = setTimeout(() => {
      questionAddRef.value.clearValidate()
    }, 30)


  }

}
// 类目
const initCourseOption = () => {
  configListApi({ "levelNum": 1 }).then(res => { saveOptions.courseOption = res.rows || [] })
}
// 类别
const initCourseOtherOption = () => {
  configRuleRequestClear('courseId')
  configListApi({ "levelNum": 2, "parentId": questionAddRequest.categoryId, }).then(res => {
    saveOptions.courseOtherOption = res.rows || []
    saveOptions.courseBankTypeOption = []
    saveOptions.subOption = []
    if (questionAddRef.value) { questionAddRef.value.clearValidate() }
  })
}
// 题库类型
const initCourseBankTypeOption = () => {
  configRuleRequestClear('courseBankTypeId')
  // configRuleRequest.testConfModeTypeCode == 'difference' ? initSubOption() : ''
  enableBankTypeListApi({ courseId: questionAddRequest.courseParentId }).then(res => { saveOptions.courseBankTypeOption = res.rows || [] })
}
// 科目
const initSubOption = () => {
  configListApi({ "levelNum": 3, "parentId": questionAddRequest.courseParentId, }).then(res => {
    saveOptions.subOption = res.rows || []
  })
}
</script>

<style scoped lang="scss">
:deep(.el-upload-list__item-info) {
  // flex-direction: row !important;
  width: fit-content;

}

:deep(.el-upload-list__item-status-label) {
  // display: block !important;
  // position: relative !important;
  // width: 20px;
  // padding-top: 5px;
  // margin-left: 15px;
}

:deep(.el-icon--close) {}

:deep(.is-success) {
  // display: flex;
  // align-items: center;
  // justify-content: center;
}

:deep(.el-input) {
  width: 400px;
}

.questionAdd-item {
  position: relative;
  margin: 0 55px;
  width: 350px;
  height: 130px;
  border: 1px solid rgba(64, 158, 255, 0.502);
  text-align: center;
  border-radius: 10px;
  margin-top: 65px;

  .questionAdd-button-item {
    transform: translateY(70px);
  }

  img {
    width: 120px;
    height: 120px;
    position: absolute;
    // border-radius: 50%;
    left: 125px;
    top: -50px;
  }

}
</style>